// 问卷集管理器 - 处理多个问卷组成的问卷集（如 assessment）
import { getQuestionnaire, getAssessConfig, getSubQuestionnaire } from './schema-loader.js'
import { visibilityEngine } from './visibility-engine.js'
import { ScoringEngine } from './scoring-engine.js'
import { extractResultDetailsFromAnswers } from './details-extractor.js'

/**
 * 问卷集管理器
 * 处理由多个子问卷组成的问卷集（如 assessment）
 */
export class QuestionnaireSetManager {
    constructor(type) {
        this.type = type;
        this.subQuestionnaires = new Map();
        this.engines = new Map();
        this.initialize();
    }

    /**
     * 初始化问卷集
     */
    initialize() {
        if (this.type === 'assessment') {
            const config = getAssessConfig();
            const assessKeys = ["a1", "a2", "a3", "a4", "a5", "a6"];
            
            for (const key of assessKeys) {
                const subQues = getSubQuestionnaire('assessment', key);
                if (subQues) {
                    this.subQuestionnaires.set(key, subQues);
                    this.engines.set(key, {
                        visibility: visibilityEngine,
                        scoring: new ScoringEngine(subQues.score_judge)
                    });
                }
            }
        }
    }

    /**
     * 获取子问卷
     * @param {string} id - 子问卷ID
     * @returns {Object} 子问卷定义
     */
    getSubQuestionnaire(id) {
        return this.subQuestionnaires.get(id);
    }

    /**
     * 获取子问卷的可见题目ID
     * @param {string} id - 子问卷ID
     * @param {Array} answers - 当前答案数组
     * @returns {Array} 可见题目ID数组
     */
    getVisibleQuestionIds(id, answers) {
        const engine = this.engines.get(id);
        const subQues = this.subQuestionnaires.get(id);
        if (!engine || !subQues) return [];
        return engine.visibility.getValidQuestionIds(Object.keys(subQues.questions), ["visible", "plain"], answers, subQues.questions);
    }

    /**
     * 处理子问卷答案
     * @param {string} id - 子问卷ID
     * @param {Array} answers - 答案数组
     * @returns {Object} 处理结果
     */
    processSubQuestionnaireAnswers(id, answers) {
        const engine = this.engines.get(id);
        const subQues = this.subQuestionnaires.get(id);
        
        if (!engine || !subQues) {
            throw new Error(`Sub-questionnaire ${id} not found`);
        }

        // 获取有效题目和答案
        const { valid_questions, valid_answers } = engine.visibility.getValidQuestionsAndAnswers(subQues.questions, answers);
        
        // 计算维度得分
        const dimensionScores = engine.scoring.calculateDimensionScores(valid_questions, valid_answers);
        
        // 匹配区间结果
        const results = engine.scoring.matchIntervalResults(dimensionScores);
        
        // 提取详情
        const details = extractResultDetailsFromAnswers(answers, subQues.questions);
        
        return {
            result: results,
            details: details
        };
    }

    /**
     * 获取所有子问卷ID
     * @returns {Array} 子问卷ID数组
     */
    getSubQuestionnaireIds() {
        return Array.from(this.subQuestionnaires.keys());
    }

    /**
     * 检查子问卷是否完成
     * @param {string} id - 子问卷ID
     * @param {Array} answers - 答案数组
     * @returns {boolean} 是否完成
     */
    isSubQuestionnaireComplete(id, answers) {
        const visibleIds = this.getVisibleQuestionIds(id, answers);
        return visibleIds.every(qId => answers[qId] !== undefined && answers[qId] !== null && answers[qId] !== '');
    }

    /**
     * 获取问卷集完成状态
     * @param {Object} allAnswers - 所有子问卷的答案 {a1: [...], a2: [...], ...}
     * @returns {Object} 完成状态
     */
    getCompletionStatus(allAnswers) {
        const status = {};
        for (const id of this.getSubQuestionnaireIds()) {
            status[id] = this.isSubQuestionnaireComplete(id, allAnswers[id] || []);
        }
        return status;
    }
}

// 创建全局实例
const assessmentSetManager = new QuestionnaireSetManager('assessment');

/**
 * 获取评估问卷集管理器
 * @returns {QuestionnaireSetManager} 问卷集管理器实例
 */
export const getAssessmentSetManager = () => assessmentSetManager;

export { assessmentSetManager };
